package touro.mancala.client.view;

import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JLabel;
import javax.swing.JPanel;

import touro.mancala.client.GameState;
import touro.mancala.client.MoveListener;
import touro.mancala.client.Board;
import touro.mancala.client.Store;

public class BoardView extends JPanel {

	private static final long serialVersionUID = -1296710295056020069L;
	private Board board;
	private GameState state = GameState.getGameState();
	
	private StoreView views[];
	private JLabel outputMessage;
	
	public static final Color BROWN = new Color(190, 143, 41);
	
	public BoardView() {
		this.board = state.getBoard();
		Store[] stores = board.getPitsAndStores();
		views = new StoreView[14];
		//sets up an array of views
		for (int i = 0; i < 14; i++){
			if (i == 6) {
				views[i] = new StoreView(stores[i]);
			} else if (i == 13) {
				views[i] = new StoreView(stores[i]);
			} else {
				views[i] = new StoreView(stores[i]);
			}
		}
		setUpOutput();
		setUpBoard();
	}

	private void setUpBoard() {
		this.setLayout(new GridBagLayout());
		GridBagConstraints constraint = new GridBagConstraints();
		constraint.fill = GridBagConstraints.BOTH;
		constraint.weightx = 1.0;
		
		constraint.weighty = 0.25;
		constraint.gridx = 0;
		constraint.gridy = 0;
		constraint.gridwidth = 8;
		constraint.gridheight = 1;
		this.add(outputMessage, constraint);
		
		constraint.weighty = 1.0;
		constraint.gridx = 0;
		constraint.gridy = 1;
		constraint.gridwidth = 1;
		constraint.gridheight = 2;
	
		this.add(views[6], constraint);
		
		constraint.gridx = 7;
		constraint.gridy = 1;
		this.add(views[13], constraint);
		
		
		
		for(int i = 0; i<13; i++) {
			if (i!=6) {
				constraint.gridheight = 1;
				if (i<6) {
					constraint.gridy = 1;
					constraint.gridx = 6-i;
				} else {
					constraint.gridy = 2;
					constraint.gridx = i-6;
				}
				this.add(views[i], constraint);
			}
		}
	}
	
	private void setUpOutput() {
		outputMessage = new JLabel("Press a pit on your side of the board to begin.");
		outputMessage.setHorizontalAlignment(JLabel.CENTER);
		outputMessage.setOpaque(true);
		outputMessage.setBackground(BoardView.BROWN);
		outputMessage.setForeground(GameState.getGameState().getColor().darker());
	}
	
	public void setMoveListener(MoveListener listener) {
		for (int i = 0; i<14; i++) {
			views[i].addMouseListener(listener);
		}
	}
	
	public Board getBoard() {
		return board;
	}
	
	public void setMessage(String message) {
		outputMessage.setText(message);
	}


}
